package com.wish.group05.financial.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.group05.base.dto.*;
import com.wish.group05.base.entity.FkBusinessCredit;
import com.wish.group05.base.entity.JrProduct;
import com.wish.group05.base.entity.JrSfLoan;
import com.wish.group05.base.service.IFkBusinessCreditService;
import com.wish.group05.base.service.IJrProductService;
import com.wish.group05.base.service.IJrSfLoanService;
import com.wish.group05.base.service.ISfContractService;
import com.wish.group05.common.core.utils.bean.BeanUtils;
import com.wish.group05.common.core.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.wish.group05.common.core.web.controller.BaseController;
import com.wish.group05.common.core.web.domain.AjaxResult;

import javax.validation.Valid;


/**
 * 【请填写功能名称】Controller
 * 
 * @author wish
 * @date 2022-06-02
 */
@RestController
@RequestMapping("/sfloan")
public class TSfContractController extends BaseController
{
    @Autowired
    ISfContractService iSfContractService;
    @Autowired
    IJrProductService jrProductService;
    @Autowired
    IJrSfLoanService iJrSfLoanService;
    @Autowired
    IFkBusinessCreditService fkBusinessCreditService;

    /**
     * 申请收房贷：保存
     * @return
     */
    @RequestMapping("savesf")
    @ResponseBody
    public AjaxResult saveContract(@Valid SaveSfLoanForm sfLoanForm){
        //--  periodsA 合同期限  periods 借款期限
        if(sfLoanForm.getPeriods() > sfLoanForm.getPeriodsA()) {
            return AjaxResult.error("借款期限大于合同有效期限");
        }

        SaveSfLoanRequestDto sd = new SaveSfLoanRequestDto();
        BeanUtils.copy(sfLoanForm, sd);
        JrProduct jrProduct = jrProductService.getById(sd.getProductId());
        //--  InstalmentPeriod 分期期限  Periods  借款期限
        if(jrProduct.getInstalmentPeriod() < sfLoanForm.getPeriods()) {
            return AjaxResult.error("借款期限大于金融产品期限");
        }

        //-- t_fk_business_credit 风控公寓授信主表  BusinessId商户id --------------------------------推代码注意推sql
        FkBusinessCredit objectBusiness = this.fkBusinessCreditService.queryObjectBusinessId(sd.getBusinessId());
        //去查询是否给该商户授权了该产品
        ViewDetailsRequestDto viewDetailsRequestDto = new ViewDetailsRequestDto();
        viewDetailsRequestDto.setBusinessId(sd.getBusinessId());
        viewDetailsRequestDto.setProductId(sfLoanForm.getProductId());
        // --------------------------------推代码注意推sql
        ZJFInformation findById = this.fkBusinessCreditService.findByBusinessAndProductId(viewDetailsRequestDto);
        //未给该商户授权该产品
        if(findById == null) {
            return AjaxResult.error("授信额度不足，请联系维数公寓客服：400-008-3363");
        }
        BigDecimal subtractProduct = BigDecimal.ZERO;
        //商户该产品总授信额度减该产品已用授信额度
        //-- usedCreditline 总资金方已用额度
        if(findById.getUsedCreditline() != null && !findById.getUsedCreditline().equals(BigDecimal.ZERO)) {
            //-- getTotalCreditline总资金方额度
            subtractProduct = findById.getTotalCreditline().subtract(findById.getUsedCreditline());
        } else {
            subtractProduct = findById.getTotalCreditline();
        }
        //申请分期金额大于该商户中的该产品剩余授信金额
        //-- getSxBalance借款金额
        if(sfLoanForm.getSxBalance().compareTo(subtractProduct) == 1) {
            return AjaxResult.error("授信额度不足，请联系维数公寓客服：400-008-3363");
        }
        //--  monthlyTotalCreditline 月资金方额度
        if(findById.getMonthlyTotalCreditline() != null && !findById.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            //商户月剩余总授信额度减已用授信额度
            BigDecimal subtractMonthly = BigDecimal.ZERO;
            //-- getMonthlyUsedCreditline 月资金方已用额度
            if(findById.getMonthlyUsedCreditline() != null && !findById.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                subtractMonthly = findById.getMonthlyTotalCreditline().subtract(findById.getMonthlyUsedCreditline());
            } else {
                subtractMonthly = findById.getMonthlyTotalCreditline();
            }
            //申请分期金额大于该商户月剩余授信金额
            if(sfLoanForm.getSxBalance().compareTo(subtractMonthly) == 1) {
                return AjaxResult.error("授信额度不足，请联系维数公寓客服：400-008-3363");
            }
        }else {
            // -- getHlMonthlyUsedCreditline 月资金方已用额度
            if(objectBusiness.getHlMonthlyTotalCreditline() != null && !objectBusiness.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
                //商户月授信额度减月已用授信额度
                BigDecimal subtractMonthly = BigDecimal.ZERO;
                // -- getHlMonthlyUsedCreditline 月资金方已用额度 getHlMonthlyUsedCreditline 维数公寓月授信额度
                if(objectBusiness.getHlMonthlyUsedCreditline() != null && !objectBusiness.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                    subtractMonthly = objectBusiness.getHlMonthlyUsedCreditline().subtract(objectBusiness.getHlMonthlyUsedCreditline());
                } else {
                    subtractMonthly = objectBusiness.getHlMonthlyTotalCreditline();
                }
                //申请分期金额大于该商户月剩余授信金额
                if(sfLoanForm.getSxBalance().compareTo(subtractMonthly) == 1) {
                    return AjaxResult.error("授信额度不足，请联系维数公寓客服：400-008-3363");
                }
            }
        }

        // -- 计算维数公寓的总授信额度
        BigDecimal hlUsedCreditline = BigDecimal.ZERO;
        // --getHlUsedCreditline  维数公寓已用授信额度 getSxBalance借款金额
        if(objectBusiness.getHlUsedCreditline() != null && !objectBusiness.getHlUsedCreditline().equals(BigDecimal.ZERO)) {
            hlUsedCreditline = objectBusiness.getHlUsedCreditline().add(sfLoanForm.getSxBalance());
        } else {
            hlUsedCreditline = sfLoanForm.getSxBalance();
        }
        objectBusiness.setHlUsedCreditline(hlUsedCreditline);

        // -- 计算维数公寓的月总授信额度
        //-- getHlMonthlyTotalCreditline维数公寓月授信额度
        if(objectBusiness.getHlMonthlyTotalCreditline() != null && !objectBusiness.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            // -- getHlMonthlyUsedCreditline 维数公寓月已用授信额度
            if(objectBusiness.getHlMonthlyUsedCreditline() != null && !objectBusiness.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = objectBusiness.getHlMonthlyUsedCreditline().add(sfLoanForm.getSxBalance());
            } else {
                hlMonthlyUsedCreditline = sfLoanForm.getSxBalance();
            }
            objectBusiness.setHlMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }

        // -- 更新时间
        objectBusiness.setUpdateTime(new Date());
        // -- 更新用户id
        objectBusiness.setUpdateUserid(sd.getLoginUserId());

        this.fkBusinessCreditService.updateById(objectBusiness);


        BigDecimal usedCreditlineProduct = BigDecimal.ZERO;
        // --  usedCreditline 总资金方已用额度
        if(findById.getUsedCreditline() != null && !findById.getUsedCreditline().equals(BigDecimal.ZERO)) {
            usedCreditlineProduct = findById.getUsedCreditline().add(sfLoanForm.getSxBalance());
        } else {
            usedCreditlineProduct = sfLoanForm.getSxBalance();
        }
        findById.setUsedCreditline(usedCreditlineProduct);
        //-- monthlyTotalCreditline 月资金方额度
        if(findById.getMonthlyTotalCreditline() != null && !findById.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if(findById.getMonthlyUsedCreditline() != null && !findById.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = findById.getMonthlyUsedCreditline().add(sfLoanForm.getSxBalance());
            } else {
                hlMonthlyUsedCreditline = sfLoanForm.getSxBalance();
            }
            findById.setMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }
        findById.setUpdateUserid(sd.getLoginUserId());
        this.fkBusinessCreditService.updateFkBusinessCreditSub(findById);
        iJrSfLoanService.saveLoan(sd);
        return AjaxResult.success();
    }



    /**
     * 申请收房贷：计算--分期
     * @return
     */
    @GetMapping("listSfLoan")
    public AjaxResult listSfLoan(SfLoanDetailRequestBean bean) throws ParseException {
        // 收房贷计算  contractId 合同id productId金融产品id
        SfContractDetailsResponseDTO sfentity = iSfContractService.
                getSfContractStagingCalculation(bean.getContractId(),bean.getProductId());
        SearchSfLoanDetailRequestDto sfdto = new SearchSfLoanDetailRequestDto();
        //工具类没有这个方法，
        BeanUtils.copy(bean,sfdto);

        sfdto.setBalance(Double.parseDouble(bean.getBalance()));	// 借款金额
        sfdto.setSxBalance(Double.parseDouble(bean.getSxBalance())); // 授信额
        sfdto.setPeriods(bean.getPeriods());	// 期数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sfdto.setStartDate(sdf.parse(bean.getStartDate())); // 合同开始日
        sfdto.setEndDate(sdf.parse(bean.getEndDate()));	// 合同结束日
        // 分期计算
        SearchSfLoanDetailsResponseDto sfr= iJrSfLoanService.getSfLoanDetail(sfdto);

        return AjaxResult.success(sfr);
    }

    @GetMapping("/ByProductList")
    public AjaxResult ByProductList()
    {
        // 获取收房贷产品列表
        List<JrProduct> list = jrProductService.list(new QueryWrapper<JrProduct>()
                .eq("jr_product_type", 2).eq("del_flg", 0));
        return AjaxResult.success(list);
    }

    @GetMapping("/getbyIdContract")
    public AjaxResult getbyIdContract(SfContractDetailsResponseDTO requestSearchSfsDto)
    {
        SfContractDetailsResponseDTO sfentity = iSfContractService.getSfContract(requestSearchSfsDto.getId());
        // 拼接房产信息   = 小区名称+ 房产信息
        sfentity.setHouseName(sfentity.getPremiseName() + sfentity.getHouseName());
        return AjaxResult.success(sfentity);
    }


    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/financialList")
    public TableDataInfo list(RequestSearchSfsDto requestSearchSfsDto)
    {
        startPage();
        List<ResponseSearchSfsDto> list = iSfContractService.financialList(requestSearchSfsDto);
        return getDataTable(list);
    }

}
